import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { header, aliyun } from '../data/config'
import { random_string, get_suffix, previewImg, imgPreviewModal } from '../data/util'

import { bank as valid_bank } from '../data/validate'

const base = url.base,
  addDeveloper = request.editOneHouseHelper,
  oneHouseHelperImg = request.oneHouseHelperImg
 

// 页面标题
const title = '壹房通助手',
  action = '添加',
  E = window.wangEditor;


let form = new Vue({
  el: '#form',
  data: () => ({
    name: '',
    //默认未选中 false 1
    isRecommend: false,
    status: '',
    bankRealname: '',
    bankCardNo: '',
    merchantBank: '',
    lockImg: '',
    islockImgLock: false,
    // 锁屏图片上传进度
    lockImgProgress: 0,
    lockImgPreview: '',
    editor: null
  }),
  mounted: function () {
    this.editor = new E('#editor');
    this.editor.create()
    valid()

  },
  methods: {
    showPreview: function () {
      this.resetPrePhoneCss();
      this.updatePreviewHtml();

      $(".preview-layer").show();
    },
    resetPrePhoneCss: function () {
      let dom = $(".preview-phone"),
        dom_left = $(window).width() / 2 - dom.width() / 2,
        dom_top = $(window).height() / 2 - dom.height() / 2,
        css_str = {
          left: dom_left + "px",
          top: dom_top + "px"
        };
      dom.css(css_str);
    },
    agreeApply: function (v) {
      this.status = v;
    },
    updatePreviewHtml: function () {
      let ifr_document = document.getElementById("preview-html").contentWindow.document,
        content = this.editor.txt.html();


      //设置正文
      if (ifr_document && content) {
        let ifr_content = $(ifr_document).find(".article-content");
        ifr_content.html(content);
      }
    },
    // 锁屏图片上传
    uploadLockImg: function () {

      let that = this,
        file = this.$refs.lockImg.files[0]

      if (!file) {
        layer.msg('没有选择文件', {
          icon: 5
        })
        return
      }

      // 检验文件类型
      let allowExt = ['jpg', 'jpeg', 'png'],
        ext = file.name.substr(file.name.lastIndexOf('.') + 1)

      if (_.indexOf(allowExt, ext) === -1) {
        layer.msg('文件格式错误,图片格式只能为' + allowExt.toString(), {
          icon: 5
        })

        return
      }
      let loading = layer.msg('图片上传中...', {
        icon: 16,
        time: 0
      })
      let formData = new FormData();
      formData.append("yftHelperImge",file);
      $.ajax({
        url: base + oneHouseHelperImg,
        headers: header,
        type: 'POST',
        data: formData,
        processData:false,
        contentType:false,
      }).xhr()
        .done(function (res) {
          layer.close(loading)
          if (res.code === 0) {
            that.isLock = false;
            that.lockImg=res.object;
            that.lockImgPreview= base +res.object;
            that.lockImgProgress=100;
            layer.msg('图片上传成功', {
              icon: 5
            })
          } else {
            layer.msg('图片上传失败', {
              icon: 5
            })
          }
          $.extend(form.$data, res.object)

        })
        .fail(function () {
          layer.close(loading)
          layer.msg('图片上传失败', {
            icon: 5
          })
        })
        .always(function () {
      })
    },
    imgPreviewModal: imgPreviewModal,
    clearImgPreview: function (e) {
      this.lockImgPreview = ''
      this.lockImg = ''
      this.$refs.lockImg.value  = ''
      this.lockImgProgress=0;
    }
  }
})

function valid() {

  let form_valid,
    $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: (e) => {
      console.log('submit!')
      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        url: base + addDeveloper,
        type: 'POST',
        contentType: 'application/json',
        headers: header,
        data: JSON.stringify({
          name: form.name,
          content: form.editor.txt.html(),
          url: form.lockImg,
          isRecommend: form.isRecommend === false ? '1' : '0',
          status: form.status,
        })
      })
        .done(function (res) {
          if (res.code === -1) {
            layer.msg(res.message, {
              icon: 5
            })
            return
          }

          layer.msg(`${action} ${title}成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data())

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function (res) {
          layer.msg(`添加${title}失败`, {
            icon: 5
          })
        })
        .always(function (res) {
          layer.close(loading_modal)
          // form.isLock = false
        })
    }
  })


  // 验证
  form_valid = $form.validate({
    errorPlacement: function (error, element) {
      error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      name: {
        required: true,
        checkUserExist: true
      },
      enterprisePrefix: {
        required: true
      },
      enterpriseName: {
        required: true
      },
      realName: {
        required: true
      },
      phone: {
        phone: true,
        required: true
      },
      merchantBank: {
        // required: true
      },
      bankCardNo: valid_bank
    }
  })

}